package adminorg;

import java.io.Serializable;
import java.util.Date;

import com.oros.db.AEFilter.FilterOperator;
import com.vaadin.data.util.filter.Compare.Equal;
import com.vaadin.ui.TextField;

public class StatisticDataHelper implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 7100624814049777762L;
	private DatabaseHelper dbHelp = null;
	public StatisticDataHelper(DatabaseHelper dbHelper){
		this.dbHelp=dbHelper;
	}
	
	public double getDataD(Date D, Object StatUseId) throws Exception{
		try{
			dbHelp.getStatisticDataContainer().removeAllContainerFilters();
			dbHelp.getStatisticDataContainer().addContainerFilter(new Equal("date",D));
			dbHelp.getStatisticDataContainer().addContainerFilter(new Equal("statisticuses",StatUseId));
			//dbHelp.getStatisticDataContainer().AppEngineAddFilter("date", FilterOperator.EQUAL, D);
			//dbHelp.getStatisticDataContainer().AppEngineAddFilter("statisticuses", FilterOperator.EQUAL, StatUseId);
			if (dbHelp.getStatisticDataContainer().size()>0){
				Object ItemId = dbHelp.getStatisticDataContainer().firstItemId();
				return new Double((Double)dbHelp.getStatisticDataContainer().getContainerProperty(ItemId, "sum").getValue());
			} else {
				return 0;
			}
		} catch (Exception e){
			e.printStackTrace();
			return 0;
		} finally{
			dbHelp.getStatisticDataContainer().removeAllContainerFilters();
		}
		
	}
	
	public TextField getDataInp(Date D, Object StatUseId) throws Exception{
		double Sum = new Double(getDataD(D,StatUseId));
		return new TextField(String.valueOf(Sum));		
	}
	
	public void SaveDate(Date D, Object StatUseId, double N){
		try{
			dbHelp.getStatisticDataContainer().removeAllContainerFilters();
			dbHelp.getStatisticDataContainer().addContainerFilter(new Equal("date",D));
			dbHelp.getStatisticDataContainer().addContainerFilter(new Equal("statisticuses",StatUseId));
			//dbHelp.getStatisticDataContainer().AppEngineAddFilter("date", FilterOperator.EQUAL, D);
			//dbHelp.getStatisticDataContainer().AppEngineAddFilter("statisticuses", FilterOperator.EQUAL, StatUseId);
			if (dbHelp.getStatisticDataContainer().size()>0){
				Object ID = dbHelp.getStatisticDataContainer().firstItemId();
				dbHelp.getStatisticDataContainer().rollback();
				dbHelp.getStatisticDataContainer().setPropertiesOfItem(ID, "sum", N);
				dbHelp.getStatisticDataContainer().commit();
			} else {
				dbHelp.getStatisticDataContainer().rollback();
				dbHelp.getStatisticDataContainer().addNewItem(new String[]{"statisticuses","date","sum"}, 
						new Object[]{StatUseId,D,N});
				dbHelp.getStatisticDataContainer().commit();
			}
		} catch (Exception e){
			e.printStackTrace();
		}
	}

}
